package rabbitmq.direct;

import com.rabbitmq.client.*;
import rabbitmq.contant.Contants;

import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws Exception {
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Contants.HOST);
        connectionFactory.setPort(Contants.PORT);
        connectionFactory.setUsername(Contants.USER_NAME);
        connectionFactory.setPassword(Contants.PASSWORD);
        connectionFactory.setVirtualHost(Contants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2.开启信道
        Channel channel = connection.createChannel();
        // 3.声明队列(使用内置交换机)
        channel.queueDeclare(Contants.DIRECT_QUEUE1,true,false,false,null);// 已存在则不会创建,不存在则会创建,
        // 不声明若队列不存在,则会报错,影响生产环境
        // 4.消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 从队列中接收到信息就会执行的内容
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // TODO
                System.out.println("接收消息: "+new String(body));
            }
        };
        channel.basicConsume(Contants.DIRECT_QUEUE1,true,consumer);

        // 等待程序执行完成

        // 5.释放资源
//        channel.close();
//        connection.close();
    }
}
